﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Op.Models;
using YouWei.Utility;
using YouWei.Utility.Logging;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Drawing;
using OF.Utility;

namespace YouWei.Op.Controllers
{
    public class ProductController : BaseController
    {
        private ProductService _service = new ProductService();
        private ProductGruopRelService _serviceRel = new ProductGruopRelService();
        private ProductImageService _serviceImg = new ProductImageService();
        private CommentService _serviceComment = new CommentService();
        private CommentDetailService _serviceCommentDetail = new CommentDetailService();
        private CommentImageService _serviceCommentImage = new CommentImageService();
        private UserInfoService _serviceUser = new UserInfoService();

        string ComplateLocalPath = ConfigHelper.GetAppSettingValue("CommentImageTmpPath"); //原图地址
        string CommentImageLocalPath = ConfigHelper.GetAppSettingValue("CommentImageLocalPath");//剪切去水印后地址
        string CommentImageLocalPathCompress = ConfigHelper.GetAppSettingValue("CommentImageListPath");//缩略图地址
        string CommentImageServerUrl = ConfigHelper.GetAppSettingValue("CommentImageServerUrl");

        // GET: Product
        public ActionResult Index()
        {
            return View();
        }

        #region 产品

        /// <summary>
        /// 产品列表查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult ParList(ProductSearchModel model)
        {
            try
            {
                var pageIndex = Convert.ToInt32(GetParam("page"));
                var pageSize = GetPageSize();
                var page = _service.Pages(pageIndex, pageSize, model);
                ViewBag.Total = page.total;
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageSize = pageSize;
                return PartialView(page.rows);
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                return PartialView();
            }
        }

        /// <summary>
        /// 产品详情
        /// </summary>
        /// <returns></returns>
        public ActionResult ProductInfo()
        {
            var id = Convert.ToInt32(GetParam("id"));
            var model = _service.Single(id);
            var imgs = _serviceImg.GetImgByProductID(id);
            ViewBag.Imgs = imgs;
            return View(model);
        }

        /// <summary>
        /// 产品列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CommentIndex()
        {
            return View();
        }

        #endregion

        #region 内容

        /// <summary>
        /// 内容列表查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult CommentParList(CommentSearchModel model)
        {
            try
            {
                var pageIndex = Convert.ToInt32(GetParam("page"));
                var pageSize = GetPageSize();
                var page = _serviceComment.Pages(pageIndex, pageSize, model);
                ViewBag.Total = page.total;
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageSize = pageSize;
                return PartialView(page.rows);
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                return PartialView();
            }
        }

        /// <summary>
        /// 内容详情
        /// </summary>
        /// <returns></returns>
        public ActionResult CommentInfo()
        {
            var id = Convert.ToInt32(GetParam("id"));
            var model = _serviceComment.GetCommentInfoById(id);
            if (model != null)
            {
                if (!string.IsNullOrWhiteSpace(model.HeadImgUrl))
                {
                    model.HeadImgUrl = CommentImageServerUrl + "/" + model.HeadImgUrl;
                }
                else
                {
                    model.HeadImgUrl = "";
                }
            }
            else
            {
                model = new CommentDto();
            }
            return View(model);
        }

        /// <summary>
        /// 内容编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult CommentEdit()
        {
            var id = GetParam<int>("id");
            var entity = new CommentDto()
            {
                CommentSection = 1
            };
            if (id > 0)
            {
                entity = _serviceComment.GetCommentInfoById(id);
                entity.Detail = new MvcHtmlString(entity.Detail).ToHtmlString();
            }
            ViewBag.CommentID = id;
            return View(entity);
        }

        /// <summary>
        /// 更新状态(审核、拒绝)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateCommentExamineStatus()
        {
            ResultData<int> rt = ResultData<int>.Error("");
            var id = GetParam<int>("id");
            var status = GetParam("status");
            if (string.IsNullOrWhiteSpace(status) || id <= 0)
            {
                rt.message = "缺少必要的参数";
                return ReturnResult(rt);
            }
            var entity = _serviceComment.Single(id);
            if (entity != null)
            {
                entity.ExamineStatus = Convert.ToInt32(status);
                entity.UpdateDate = DateTime.Now;
                var res = _serviceComment.Update(entity);
                if (res)
                    rt.status = 0;
                else
                    rt.message = "修改状态失败";
            }
            else
            {
                rt.message = "id不正确，内容不存在";
            }
            return ReturnResult(rt);
        }

        /// <summary>
        /// 设置热门
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateCommentIsHot()
        {
            ResultData<int> rt = ResultData<int>.Error("");
            var id = GetParam<int>("id");
            var isHot = GetParam("isHot");
            if (string.IsNullOrWhiteSpace(isHot) || id <= 0)
            {
                rt.message = "缺少必要的参数";
                return ReturnResult(rt);
            }
            var entity = _serviceComment.Single(id);
            if (entity != null)
            {
                //丽人馆只允许存在1个置顶，在更新之前先取消之前的置顶
                if (EConvert.ToInt(isHot) == 2)
                {
                    _serviceComment.CancelCommentIsHot();
                    //置顶之前，判断浏览量和点赞量小于50则随机50-300
                    entity.PageViews = entity.PageViews < 50 ? new Random().Next(50, 300) : entity.PageViews;
                    entity.PraiseCount = entity.PraiseCount < 50 ? new Random().Next(50, 300) : entity.PraiseCount;
                }
                entity.IsHot = Convert.ToInt32(isHot);
                entity.UpdateDate = DateTime.Now;
                var res = _serviceComment.Update(entity);
                if (res)
                    rt.status = 0;
                else
                    rt.message = "修改失败";
            }
            else
            {
                rt.message = "id不正确，内容不存在";
            }
            return ReturnResult(rt);
        }

        [HttpPost]
        public ActionResult CommentSave(CommentDto model)
        {
            ResultData<int> rt = ResultData<int>.Success();
            var commentId = GetParam<int>("id");
            if (string.IsNullOrWhiteSpace(model.CommentName))
            {
                rt.message = "文章名称不能为空";
                rt.status = -1;
                return ReturnResult(rt);
            }

            if (string.IsNullOrWhiteSpace(model.CommentDesc))
            {
                rt.message = "简介不能为空";
                rt.status = -1;
                return ReturnResult(rt);
            }
            var entity = new Comment()
            {
                CommentDesc = model.CommentDesc,
                CommentName = model.CommentName,
                CommentType = model.CommentType,
                HeadImgUrl = model.HeadImgUrl,
                IsShow = model.IsShow,
                IsHot = 0,//默认非热门
                IsActive = 1,
                UpdateDate = DefaultTime,
                CommentSection = model.CommentSection
            };
            entity.CommentLink = model.CommentLink;
            model.Detail =new CommentDetailProcess().ProcessDetail(model.Detail);
            //编辑和新增
            if (commentId > 0)
            {
                entity = _serviceComment.Single(commentId);
                entity.CommentDesc = model.CommentDesc;
                entity.CommentName = model.CommentName;
                entity.CommentType = model.CommentType;
                entity.HeadImgUrl = model.HeadImgUrl;
                entity.IsShow = model.IsShow;
                entity.CommentSection = model.CommentSection;
                entity.CommentLink = model.CommentLink;
                entity.CommentID = commentId;
                entity.UpdateDate = DateTime.Now;
                CommentUpdate(entity, model.Detail, commentId);
                rt.data = commentId;
            }
            else
            {
                //随机取一个用户存进去，假装真实用户  liucx
                var user = _serviceUser.GetUserInfoRandom();
                var userId = user == null ? 0 : user.UserID;
                entity.UserID = userId;
                entity.CreateDate = DateTime.Now;
                //置顶之前，判断浏览量和点赞量小于50则随机50-300
                entity.EvaluateCount = new Random().Next(50, 300);
                entity.PraiseCount = new Random().Next(50, 300);
                rt.data = CommentAdd(entity, model.Detail);
            }
            return ReturnResult(rt);
        }

        /// <summary>
        /// 更新文章上下架状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateShow()
        {
            ResultData<int> rt = ResultData<int>.Error("");
            var id = GetParam<int>("id");
            var isShow = GetParam("isShow");
            if (string.IsNullOrWhiteSpace(isShow) || id <= 0)
            {
                rt.message = "缺少必要的参数";
                return ReturnResult(rt);
            }
            var entity = _serviceComment.Single(id);
            if (entity != null)
            {
                entity.IsShow = Convert.ToInt32(isShow);
                entity.UpdateDate = DateTime.Now;
                var res = _serviceComment.Update(entity);
                if (res)
                    rt.status = 0;
                else
                    rt.message = "修改失败";
            }
            else
            {
                rt.message = "id不正确，内容不存在";
            }
            return ReturnResult(rt);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CommentDelete()
        {
            ResultData<int> rt = ResultData<int>.Error("");
            var id = GetParam<int>("id");
            if (id <= 0)
            {
                rt.message = "缺少必要的参数";
                return ReturnResult(rt);
            }
            var entity = _serviceComment.Single(id);
            if (entity != null)
            {
                entity.IsActive = 0;
                entity.UpdateDate = DateTime.Now;
                var res = _serviceComment.Update(entity);
                if (res)
                    rt.status = 0;
                else
                    rt.message = "删除成功";
            }
            else
            {
                rt.message = "id不正确，内容不存在";
            }
            return ReturnResult(rt);
        }
    
        /// <summary>
        /// 添加文章和详情
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="detail"></param>
        /// <returns></returns>
        protected int CommentAdd(Comment entity, string detail)
        {
            //存文章信息
            var commentId = Convert.ToInt32(_serviceComment.Insert(entity));
            //存文章详情
            var detailEntity = new CommentDetail()
            {
                CreateDate = DateTime.Now,
                Detail = detail,
                UpdateDate = DefaultTime,
                CommentID = commentId
            };
            _serviceCommentDetail.Insert(detailEntity);
            if (!string.IsNullOrWhiteSpace(detail))
                CommentImageAdd(detail, commentId);
            return commentId;
        }

        /// <summary>
        /// 更新文章和详情
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="detail"></param>
        /// <param name="commentId"></param>
        protected void CommentUpdate(Comment entity, string detail, int commentId)
        {
            _serviceComment.Update(entity);
            var detailEntity = _serviceCommentDetail.GetDetailByCommentID(commentId);
            if (detailEntity == null)
                detailEntity = new CommentDetail() { CreateDate = DateTime.Now };
            detailEntity.Detail = detail;
            detailEntity.UpdateDate = DateTime.Now;
            _serviceCommentDetail.Update(detailEntity);
            //先删除文章ID下的所有图片
            _serviceCommentImage.DeleteByCommentID(commentId);
            //再存图片
            CommentImageAdd(detail, commentId);
        }

        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="detail"></param>
        /// <param name="commentId"></param>
        protected void CommentImageAdd(string detail, int commentId)
        {
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(detail);
            //处理img图片
            var imgList = new List<CommentImage>();

            //作为html解析
            var imageDoms = htmlDoc.DocumentNode.SelectNodes("//img");
            if (imageDoms != null)
            {
                var index = 1;
                foreach (var item in imageDoms)
                {
                    var srcDom = item.Attributes["src"];
                    if (srcDom == null)
                        srcDom = item.Attributes["data-src"];
                    if (srcDom == null)
                        continue;
                    string src = srcDom.Value;
                    var imgEntity = new CommentImage()
                    {
                        CommentID = commentId,
                        ImageSort = index,
                        CreateDate = DateTime.Now,
                        ImageName = "",
                        IsActvie = 1,
                        UpdateDate = DefaultTime,
                        ImageUrl = src
                    };
                    imgList.Add(imgEntity);
                    index += 1;
                }
                _serviceCommentImage.Insert(imgList);
            }
        }

        /// <summary>
        /// 根据公众号获取内容
        /// </summary>
        /// <param name="wxLink">微信链接</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetCommentDetailByLink(string wxLink)
        {
            ResultData<CommentDto> rt = ResultData<CommentDto>.Success();
            if (string.IsNullOrWhiteSpace(wxLink))
            {
                return ReturnResult(ResultData<CommentDto>.Error("文章链接不允许为空"));
            }
            rt.data = SpidersWxComment.GetWxCommon(wxLink);
            return ReturnResult(rt);
        }

        /// <summary>
        /// 上传图片公用方法
        /// </summary>
        public ActionResult UploadImg()
        {
            var szReturn = ResultData<CarImageReturn>.Error("上传失败");
            var fudCommon = HttpContext.Request.Files[0];
            CarImageReturn oReturn = new CarImageReturn();

            string fileName = Path.GetFileName(fudCommon.FileName); //得到文件名
            string fileExtension = Path.GetExtension(fudCommon.FileName);//'获取扩展名
            string fileTrueName = Guid.NewGuid().ToString("N") + fileExtension;

            string httpImgUrl = CommentImageServerUrl + "/" + fileTrueName;
            try
            {
                var filePath = Path.Combine(CommentImageLocalPath, fileTrueName);
                fudCommon.SaveAs(filePath);

                using (var img = Image.FromFile(filePath))
                {
                    //缩略图
                    PictureUtility.ComPressJPEG(img, img.Width, img.Height)
                                  .Save(Path.Combine(CommentImageLocalPathCompress, fileTrueName));
                }


                szReturn = ResultData<CarImageReturn>.Success(new CarImageReturn
                {
                    ImgUrl = fileTrueName,//asdf.png
                    PhysicalImgUrl = filePath,  //C:\\asdf.png
                    HttpImgUrl = httpImgUrl,  //http:\\asdf.png
                    Width = 0,
                    Height = 0,
                   // Size = Convert.ToDecimal(fudCommon.ContentLength / 1024),
                    ImgUploadName = fudCommon.FileName
                });

            }
            catch (Exception ex)
            {
                szReturn = ResultData<CarImageReturn>.Error("上传文件时发生异常:" + ex.Message);
            }
            return ReturnResult(szReturn);
        }
        #endregion

    }
}